<template>
    <div class="content">
        <van-form colon @submit="onSubmit" validate-first @failed="onFailed">
            <div class="title">Basic Information</div>
            <van-field
                    v-model="formItem.name"
                    name="name"
                    label="Name"
                    placeholder="Please fill in your real name."
                    :maxlength="20"
                    @focus="bodyScrollTop"
                    @blur="bodyScrollTop"
                    :rules="[{ validator: nameValidator,required: true, message: 'Please fill in your real name.' }]"></van-field>
            <van-field
                    label="Sex"
            >
                <template #input>
                    <van-radio-group v-model="formItem.sex" direction="horizontal">
                        <van-radio name="男" icon-size="22px">male</van-radio>
                        <van-radio name="女" icon-size="22px">female</van-radio>
                    </van-radio-group>
                </template>
            </van-field>
            <van-field
                    v-model="formItem.age"
                    name="age"
                    label="Age"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    placeholder="Please fill in your age."
            />
            <van-field
                    v-model="formItem.is_permanent"
                    name="Nationality"
                    label="Nationality"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    placeholder="Please fill in your Nationality."
            />
            <van-field
                    v-model="formItem.card_no"
                    name="card_no"
                    label="Passport No"
                    @blur="bodyScrollTop"
                    @focus="bodyScrollTop"
                    placeholder="Please fill in the real passport number."
            />
            <van-field
                    v-model="formItem.tel"
                    name="tel"
                    label="Cellphone No"
                    :rules="phoneRules"
                    placeholder="Please type in the correct mobile phone number."
                    @focus="bodyScrollTop"
                    @blur="bodyScrollTop"/>
            <area-page ref="areaPage" @result="bodyScrollTop"></area-page>
            <div class="title">Recent travel history.</div>
            <recent-situation ref="recentSituation" @result="bodyScrollTop"></recent-situation>

            <div class="div-bot">
                <van-button :disabled="submitDisabled" :loading="submitLoading" round block type="info"
                            native-type="submit" class="city-card-common-btn">
                    APPLY
                </van-button>
            </div>
        </van-form>
        <!-- 公众号二维码-->
        <van-popup v-model="successModel" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="success-title">
                <div>Press and hold to identify QR code to follow the official accounts and check your pass code.</div>
                <!--                <div>查 看 通 行 证</div>-->
            </div>
            <div class="success-code">
                <img :src="require('@/assets/images/waiji.png')"/>
            </div>
        </van-popup>
        <!--    提示说明    -->
        <van-popup v-model="showReadme" :close-on-click-overlay="false" safe-area-inset-bottom
                   :style="{ width: '80%', position: 'fixed', top: '50%', borderRadius: '10px' }">
            <div class="readme-popup">
                <div class="readme-popup-title">WARM TIPS</div>
                <div class="readme-popup-content">
                    <p>According to the "Law of the People's Republic of China on the Prevention and Control of
                        Infectious Diseases" and the relevant circulars of Shenyang Municipal COVID-19 Epidemic
                        Prevention and Control Headquarters, domestic and foreign visitors should proactively apply for
                        a "Health Pass Code" as an individual's electronic pass in Shenyang. This application will be
                        included in the personal credit evaluation. Please take the initiative to apply and truthfully
                        report all the information. </p>
                    <!--                    <p>本次“健康通行码”申领将纳入个人征信评价，请您主动办理，如实填报各项信息。</p>-->
                    <p>Thank you for your support to the city's efforts in epidemic prevention and control！</p>
                    <div class="tong-yi-box">
                        <van-checkbox v-model="tongyi" style="float: left;margin: 0px 8px;"></van-checkbox>
                        <div>
                            I take the initiative to apply for a "Health Pass Code". I voluntarily report personal
                            information, and promise to fill in the information truthfully and accurately, if not, I am
                            willing to bear corresponding legal liabilities.
                        </div>
                    </div>
                </div>
                <div class="readme-popup-btn">
                    <van-button block type="info"
                                native-type="button"
                                size="small"
                                class="readme-popup-btn-sm"
                                @click="choose">
                        APPLY
                    </van-button>
                </div>
            </div>

        </van-popup>

    </div>
</template>

<script>
import { insertCountrypermit, getOpenidMsg } from '@/api/yi-qing-fang-kong.js'
// 工具
import { identityCodeValid, identityMobile } from '@/libs/tools'
import AreaPage from './wai-ji-components/area-page/index'
import RecentSituation from './wai-ji-components/recent-situation/index'
import wx from 'weixin-js-sdk'
import dist from '@/libs/dist'

export default {
  components: {
    RecentSituation,
    AreaPage
  },
  data () {
    this.phoneRules = [
      { required: true, message: 'Please type in your mobile phone number. ' },
      { validator: this.phoneValidator, message: 'Wrong mobile phone number format.' }
    ]
    return {
      formItem: {
        // 表单数据
        name: '',
        card_no: '',
        tel: '',
        area_type: '', // 区域类型
        area_id: '',
        street_id: '',
        community_id: '',
        area: '',
        street: '',
        community: '',
        loc_province: '', // 地图选取后的省
        loc_city: '', // 地图选取后的市
        loc_title: '', // 地图选取后的地址名
        loc_address: '', // 地图选取后的具体地址
        house_num: '', // 门牌号
        is_hubei: '',
        is_contact: '',
        health_state: '',
        temp: ''
      },
      sendBtnType: false,
      showReadme: true,
      tongyi: true,
      submitDisabled: false,
      submitLoading: false,
      successModel: false,
      routeObj: {}, // 路由对象
      language: dist.language
    }
  },
  computed: {},
  methods: {
    failNotice (title) {
      this.$notify({ type: 'danger', message: title })
    },
    idCardValidator (val) {
      // 身份证
      const reg1 = identityCodeValid(val)
      if (!reg1.pass) {
        // this.failNotice('请检查身份证格式！')
        return false
      }
    },
    phoneValidator (val) {
      return identityMobile(val)
    },
    nameValidator (val) {
      if (val === '') {
        this.failNotice('Please fill in your name.')
        return false
      }
      return true
    },
    // cardTypeValidator (val) {
    //   if (val === '') {
    //     this.failNotice('请选择证件类型')
    //     return false
    //   }
    //   return true
    // },
    onFailed (errorInfo) {
      this.failNotice(errorInfo.errors[0].message)
      console.log('failed', errorInfo)
    },
    onSubmit (value) {
      console.log('表单提交', this.formItem)
      // 校验姓名
      if (!this.formItem.name) {
        this.failNotice('Please fill in your name.')
        return false
      }
      if (!this.formItem.sex) {
        this.failNotice('Please select your gender.')
        return false
      }
      if (!this.formItem.age) {
        this.failNotice('Please fill in your age.')
        return false
      }
      if (!this.formItem.is_permanent) {
        this.failNotice('Please fill in your nationality.')
        return false
      }
      if (!this.formItem.card_no) {
        this.failNotice('Please fill in the real passport number.')
        return false
      } else {
        if (this.formItem.card_no.length < 6) {
          this.failNotice('Please fill in the real passport number.')
          return false
        }
      }

      // 校验证件号
      // if (!this.formItem.card_no) {
      //   this.failNotice('Please fill in passport number.')
      //   return false
      // } else {
      //   const rtn = identityCodeValid(this.formItem.card_no)
      //   // console.log('身份证校验原因', rtn.tip)
      //   // console.log('身份证校验状态', rtn.pass)
      //   if (!rtn.pass) {
      //     this.failNotice(rtn.tip)
      //     return false
      //   }
      // }
      // 校验手机号
      if (!identityMobile(this.formItem.tel)) {
        this.failNotice('Please type in the correct mobile phone number.')
        return false
      }
      // 区域部分
      const areaPageData = this.$refs.areaPage.checkForm()

      // 近期情况
      const recentSituationData = this.$refs.recentSituation.checkForm()

      // 姓名去空格处理
      this.formItem.name.toString().replace(/\s/ig, '')
      // 手机号去空格处理
      this.formItem.tel.toString().trim()
      // 身份证去空格处理
      this.formItem.card_no.toString().trim()

      console.log('区域组件', areaPageData)
      console.log('近期情况组件', recentSituationData)
      if (areaPageData && recentSituationData) {
        // 组件数据处理
        this.formItem.area_type = areaPageData.area_type
        this.formItem.area_id = areaPageData.area.id
        this.formItem.area = areaPageData.area.text
        this.formItem.street_id = areaPageData.street.id
        this.formItem.street = areaPageData.street.text
        this.formItem.community_id = areaPageData.community.id
        this.formItem.company_code = !this.$common.xeUtils.isEmpty(areaPageData.community.company_code) ? areaPageData.community.company_code : areaPageData.street.company_code
        this.formItem.community = areaPageData.area_type === '1' ? areaPageData.community.text : areaPageData.cunValue
        this.formItem.house_num = areaPageData.house_num
        // this.formItem.loc_title = areaPageData.title
        // this.formItem.loc_address = areaPageData.address
        this.formItem.loc_title = areaPageData.address
        this.formItem.loc_province = areaPageData.province
        this.formItem.loc_city = areaPageData.city
        this.formItem.longitude = areaPageData.lng
        this.formItem.latitude = areaPageData.lat
        // this.formItem.address = this.formItem.loc_province + this.formItem.loc_city + this.formItem.loc_title + this.formItem.loc_address
        // this.formItem.is_hubei = recentSituationData.is_hubei
        this.formItem.is_contact = recentSituationData.is_contact
        this.formItem.health_state = recentSituationData.health_state_copy.join('^')
        this.formItem.health_state.replace(/,/g, '^')
        this.formItem.temp = recentSituationData.temp
        this.formItem.stay_city = recentSituationData.stay_city
        // 校验成功后插入
        console.log('校验成功-进开始行插入', this.formItem)
        this.insertCountrypermitAction()
      }
    },
    // 表单提交
    insertCountrypermitAction () {
      console.log('表单最终提交内容', this.formItem)
      // 表单提交
      this.successModel = false
      this.submitDisabled = false
      this.submitLoading = true
      insertCountrypermit(this.formItem).then(ret => {
        if (ret.data.errcode === 0) {
          this.submitDisabled = true
          this.submitLoading = false
          console.log('保存回调', ret.data.data)
          window.localStorage.removeItem('formData')
          if (this.$route.query.selfTs === 'selfTs') {
            this.$dialog.alert({
              title: 'WARM TIPS',
              message: 'Thank you for your support and cooperation. Your application information has been submitted successfully. The verification result will be sent to you via WeChat official account later.'
            }).then(() => {
              this.$common.wxCallBack(function () {
                wx.closeWindow()
              })
            })
          } else {
            // this.successModel = true
            this.$dialog.alert({
              message: this.language.successAlertNow
            }).then(() => {
              wx.closeWindow()
            })
          }
          // this.$dialog.alert({
          //   message: '您的电子通行证已生成!'
          // }).then(() => {
          //   this.$router.push({
          //     name: 'epidemic-submit-success',
          //     query: {}
          //   })
          // })
        } else {
          this.successModel = false
          this.submitDisabled = false
          this.submitLoading = false
          this.failNotice(ret.data.errmsg)
        }
      })
    },
    getOpenidInfoAction () {
      getOpenidMsg().then(ret => {
        console.log('判断是否注册过', ret.data)
        if (ret.data.errcode === 0) {
          if (!this.$common.xeUtils.isEmpty(ret.data.data.result)) {
            // this.successModel = true
            // this.$router.push({
            //  name: 'epidemic-submit-success',
            //  query: {}
            // })
            if (ret.data.data.result.type === '1') {
              this.$router.push({
                name: 'epidemic-submit-success-waiji',
                query: {}
              })
            } else {
              this.$dialog.alert({
                message: this.language.successAlertNow
              }).then(() => {
                wx.closeWindow()
              })
            }
          }
        } else {
          // this.failNotice(ret.data.errmsg)
        }
      })
    },
    // 去苹果机型白边
    bodyScrollTop () {
      winToTop()
      this.setStorage(this.formItem)
    },
    setStorage (formData) {
      window.localStorage.setItem('formData', JSON.stringify(formData))
    },
    choose () {
      this.showReadme = !this.tongyi
    }

  },
  mounted () {
    // 获取路由信息
    this.routeObj = this.$route.query
    console.log('表单页面路由信息', this.routeObj)
    // 获取登录信息
    this.getOpenidInfoAction()
    // 获取本地表单数据
    if (window.localStorage.getItem('formData')) {
      this.formItem = JSON.parse(window.localStorage.getItem('formData'))
      console.log('表单页面表单数据', this.formItem)
      window.localStorage.removeItem('formData')
    }
    // 区域菜单数据预处理
    console.log('表单信息', this.formItem)
  },
  watch: {
    formItem () {
      console.log('表单变化啦')
    }
  }
}
</script>

<style scoped>
    /deep/ .van-field__label {
        min-width: 5.625rem;
        margin-right: 10px;
        width: auto;
    }

    .mobile-verify-code {
        display: flex;
        justify-content: center;
        padding: 15px;
    }

    .success-code {
        display: flex;
        justify-content: center;
        padding: 5px 15px 10px;
    }

    .success-title {
        padding: 5px;
        text-align: center;
    }

    .van-radio {
        float: left;
        margin-right: 10px;
    }

    .van-popup /deep/ .van-ellipsis {
        font-size: 0.95rem;
    }

    .title {
        width: 100%;
        padding: 0.625rem 0.9375rem;
        font-size: 12px;
    }

    .action-item .van-cell__title {
        -webkit-box-flex: inherit;
        -webkit-flex: inherit;
        flex: inherit;
        width: 5.625rem;
    }

    .content {
        width: 100%;
        background-color: #F5F5F5;
        box-sizing: border-box;
        -webkit-box-sizing: border-box;
    }

    .content >>> .van-cell {
        margin: 0 2%;
        width: 96%;
        font-size: 12px;
    }

    .content >>> .van-dialog__content {
        padding: 10px;
        text-align: center;
    }

    .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value .van-field__body .van-field__control {
        font-size: 12px;
    }

    .content >>> .van-cell__value {
        text-align: left;
    }

    .div-bot {
        margin: 10px;
    }

    .div-bot >>> .van-button--info {
        border: 1px solid #75ACDC;
    }

    .div-bot >>> .van-button {
        height: 2.5rem;
    }

    .city-card-common-btn {
        color: white;
        font-size: 12px;
        padding: 0;
        width: 100%;
        border-radius: 5px;
        text-align: center;
        background-color: #75ACDC;
    }

    .content >>> .van-cell__value {
        /*flex: inherit;*/
        font-size: 12px;
    }

    .content >>> .value-item .van-cell__value {
        width: 100%;
    }

    .van-action-sheet__cancel, .van-action-sheet__item {
        font-size: 12px;
    }

    .van-cell__value span {
        /*color: black;*/
    }

    .van-dropdown-menu {
        height: 25px;
    }

    .van-hairline--top-bottom::after {
        border-width: 0px 0px;
    }

    .chaochu >>> .van-cell__value {
        width: 100%;
    }

    .div1 >>> .van-cell__value {
        width: 100%;
    }

    .div2 >>> .van-cell__value {
        width: 100%;
    }

    .other-info .van-field__label.radio-item, .tou .van-field__label.radio-item {
        width: 8.625rem;
    }

    .suggest.van-cell.van-field span {
        width: 5rem;
    }

    .readme-popup {
        padding: 25px;
    }

    .readme-popup .readme-popup-title {
        text-align: center;
        color: red;
        font-weight: bold;
        text-decoration: underline;
    }

    .readme-popup p {
        margin: 5px 0 5px 0;
        font-size: 12px;
        text-indent: 25px
    }

    .readme-popup-btn {
        display: flex;
        justify-content: center;
        margin-top: 10px;
    }

    .readme-popup-btn-sm {
        width: 45%;
    }

    .tong-yi-box {
        font-size: 12px;
    }

    .tong-yi-box >>> .van-checkbox__icon {
        font-size: 15px;
    }

    /*.content >>> .van-button--small{*/
    /*    padding: 0;*/
    /*}*/
</style>
